package homework;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class LoginRegist {
	final static String ADDRESS = "User.txt";
	private ArrayList<User> encapsulation() throws IOException{
		ArrayList<User> list = new ArrayList<User>();
		FileReader fr = new FileReader(ADDRESS);
		String temp = "";
		int data;
		while((data = fr.read()) != -1){
			if(data != '\r'){
				temp += (char)data;
			}else{
				String[] userData = temp.split(":");
				User user = new User(userData[0], userData[1]);
				list.add(user);
				temp = "";
			}
		}
		fr.close();
		return list;
	}
	
	public boolean login(String account, String password) throws IOException{
		User loginUser = new User(account,password);
		return encapsulation().contains(loginUser);
	}
	
	public boolean regist(String account, String password) throws IOException{
		FileWriter fw = new FileWriter(ADDRESS,true);
		for (User arr : encapsulation()) {
			if(arr.getAccount().equals(account)){
				return false;
			}
		}
		fw.write((account+":"+password+"\r").toCharArray());
		fw.flush();
		fw.close();
		return true;
	}
}
